﻿using System.Collections.Generic;
using System.Text;

namespace Jayden.Dll.Core.Extensions
{
	public static class StringExtensions
	{

		public static string ToLowerFirst(this string text)
		{
			if (text.Length == 0)
				return text;
			if (text.Length == 1)
				return text.ToLower();
			char first = char.ToLower(text[0]);
			return first + text.Substring(1);
		}

		public static string ToUpperFirst(this string text)
		{
			if (text.Length == 0)
				return text;
			if (text.Length == 1)
				return text.ToUpper();
			char first = char.ToUpper(text[0]);
			return first + text.Substring(1);
		}

		public static string CamelCase(this string text)
		{
			HashSet<char> ignoredChars = new HashSet<char>(new char[] { ' ', '-', '/', '\\' });
			bool upperCase = false;
			StringBuilder builder = new StringBuilder();
			text = text.Trim();
			for (int c = 0; c < text.Length; c++)
			{
				if (ignoredChars.Contains(text[c]))
					upperCase = true;
				else if (upperCase)
				{
					builder.Append(char.ToUpperInvariant(text[c]));
					upperCase = false;
				}
				else
					builder.Append(text[c]);
			}
			return builder.ToString();
		}

		public static string UnCamelCase(this string text, char spacing = '-')
		{
			StringBuilder builder = new StringBuilder();
			text = text.Trim();
			for (int c = 0; c < text.Length; c++)
			{
				if (c != 0 && char.IsUpper(text[c]))
					builder.Append(spacing);
				builder.Append(char.ToLowerInvariant(text[c]));
			}
			return builder.ToString();
		}

		public static bool Contains(this string text, string value, int startIndex, int length)
		{
			int max = startIndex + length - value.Length;
			for (int c = startIndex; c < max; c++)
			{
				int d=0;
				for (; d < value.Length; d++)
				{
					if (text[c + d] != value[d])
						break;
				}
				if (d == text.Length)
					return true;
			}
			return false;
		}

		public static string ToUserFriendlyByteLength(ulong value)
		{
			if(value < 1024)
				return value + " bytes";
			if(value < 1024 * 1024)
				return (int)(value / 1024) + " Kbytes";
			if(value < 1024 * 1024 * 1024)
				return (int)(value / (1024 * 1024)) + " Mbytes";
			return (int)(value / (1024 * 1024 * 1024)) + " Gbytes";
		}
	}
}
